package com.eagle.scali.contentcenter.configuration;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.core.Balancer;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.cloud.alibaba.nacos.ribbon.NacosServer;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 根据配置的地区集群（yml配置）以及Nacos的权重（Nacos配置）来制定
 * 负载均衡策略
 */
@Slf4j
public class NacosSameClusterWeightedRule extends AbstractLoadBalancerRule {
    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {

    }

    @Override
    public Server choose(Object key) {
        try {
            // 拿到配置文件中的集群名称 GZ
            String clusterName = nacosDiscoveryProperties.getClusterName();
			String targetVersion = this.nacosDiscoveryProperties.getMetadata().get("target-version");



            BaseLoadBalancer loadBalancer = (BaseLoadBalancer) this.getLoadBalancer();
            // 想要请求的微服务的名称
            String name = loadBalancer.getName();

            // 拿到服务发现的相关API
            NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();

            // 1. 找到指定服务的所有实例 A
            List<Instance> instances = namingService.selectInstances(name, true);

            // 2. 过滤元数据（如v1,v2版本对应）
			List<Instance> metadataMatchInstances = instances;
			// 如果配置了版本映射，那么只调用元数据匹配的实例
			if (StringUtils.isNotBlank(targetVersion)) {
				metadataMatchInstances = instances.stream()
						.filter(instance -> Objects.equals(targetVersion, instance.getMetadata().get("version")))
						.collect(Collectors.toList());
				if (CollectionUtils.isEmpty(metadataMatchInstances)) {
					log.warn("未找到元数据匹配的目标实例！请检查配置。targetVersion = {}, instance = {}", targetVersion, instances);
					return null;
				}
			}

			// 3. 过滤集群数据（如对应机房的集群）
			List<Instance> clusterMetadataMatchInstances = metadataMatchInstances;
			// 如果配置了集群名称，需筛选同集群下元数据匹配的实例
			if (StringUtils.isNotBlank(clusterName)) {
				clusterMetadataMatchInstances = metadataMatchInstances.stream()
						.filter(instance -> Objects.equals(clusterName, instance.getClusterName()))
						.collect(Collectors.toList());
				if (CollectionUtils.isEmpty(clusterMetadataMatchInstances)) {
					clusterMetadataMatchInstances = metadataMatchInstances;
					log.warn("发生跨集群调用。clusterName = {}, targetVersion = {}, clusterMetadataMatchInstances = {}", clusterName, targetVersion, clusterMetadataMatchInstances);
				}
			}


			/**
			 * 4. 基于权重的负载均衡算法，返回1个实例
			 *
			 * 跟踪NamingService#selectOneHealthyInstance(name)源码
			 * 得到Balancer#getHostByRandomWeight(hosts)，参考其实现，由于getHostByRandomWeight是protected
			 * 需要一个类去extends Balancer才能调到protected方法（参考ExtendBalancer实现）
			 */
            Instance instance = ExtendBalancer.getHostByRandomWeight2(clusterMetadataMatchInstances);
            log.info("选择的实例是 port = {}, instance = {}", instance.getPort(), instance);

            return new NacosServer(instance);
        } catch (NacosException e) {
            log.error("发生异常了", e);
            return null;
        }
    }
}

class ExtendBalancer extends Balancer {
	//提升getHostByRandomWeight访问权限
    public static Instance getHostByRandomWeight2(List<Instance> hosts) {
        return getHostByRandomWeight(hosts);
    }
}